/**
 * refactoring by zhouli on 2019/3/14.
 * 试用账号注册入口(左下角)
 */
import React from 'react';
import {connect} from 'react-redux';
import {messages, sortMenu} from 'share/common';
import 'styles/main/components/try-register.scss';
import {Checkbox, Col, Icon, Modal, Row, Tag, message} from "antd";
import ListSort from "components/list-sort";
import menuRoute from "routes/menuRoute";
import NullDataImg from "images/personal-setting/null-data.png";
import menuControl from "components/method/menuControl";
import mainService from "../../main.service";

const commonFunc = {
  PERSONAL_MODE: [],
  ADMIN_MODE: {
    TENANT_MODE: [],
    COMPANY_MODE: []
  }
};

class MenuSort extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      commonFunc: commonFunc,
      //兼容老权限，还有一个租户，
      menu: menuControl.getMenu({
        userPermission: props.userPermission,
        menu: menuRoute.menu,
        user: props.user
      }),
    }
  }

  componentDidMount() {
    this.initSettingConfig();
  }

  //初始化配置数据
  initSettingConfig = () => {
    const { menu } = this.state;
    const { tenantMode } = this.props;
    let menuConfigTemp = {};
    let commonFuncTemp = localStorage.getItem("hly.commonFunction") ? JSON.parse(localStorage.getItem("hly.commonFunction")) : commonFunc;
    if (localStorage.getItem(`hly.menuConfig.${tenantMode ? "tenantMode" : "companyMode"}`)) {
      menuConfigTemp = JSON.parse(localStorage.getItem(`hly.menuConfig.${tenantMode ? "tenantMode" : "companyMode"}`))
    } else {
      menu.map(item => {
        if (item.subMenu) {
          let subMenu = [];
          item.subMenu.map(item => subMenu.push(item.key));
          menuConfigTemp[item.key] = subMenu;
        } else {
          menuConfigTemp[item.key] = null
        }
      })
    }

    this.setState({
      menuConfig: menuConfigTemp,
      commonFunc: commonFuncTemp
    });
  };


  handleClickMenu = menuItem => {
    const { selectedKey } = this.state;
    if(!menuItem.subMenu) return;
    this.setState({
      selectedKey: menuItem.key === selectedKey ? null : menuItem.key,
      animatedFlag: false
    }, () => {
      this.setState({ animatedFlag: true })
    })
  };

  handleSortMenu = (e) => {
    if (e.length) {
      const {menuConfig} = this.state;
      let menuList = [];
      let menuKeys = Object.keys(menuConfig);
      let tempMenuConfig = {};
      let tempNullMenuConfig = {};
      e.map((item) => {
        menuList.push(item.key);
      });
      menuList.map(item => {
        tempMenuConfig[item] = menuConfig[item] ? menuConfig[item] : null;
      });
      menuKeys.map(item => {
        if (menuList.indexOf(item) === -1) {
          tempNullMenuConfig[item] = menuConfig[item] ? menuConfig[item] : null;
        }
      });
      this.setState({menuConfig: {...tempMenuConfig, ...tempNullMenuConfig}});
    } else {
      return false;
    }
  };

  handleSortSubMenu = (e) => {
    const { selectedKey } = this.setState;
    if (e.length) {
      const {menuConfig} = this.state;
      let menuConfigTemp = {...menuConfig};
      let menuList = [];
      e.map((item) => {
        menuList.push(item.key);
      });
      menuConfigTemp[selectedKey] = menuList;
      this.setState({menuConfig: menuConfigTemp});
    } else {
      return false;
    }
  };

  onSaveConfig = () => {
    const { tenantMode, menuConfig } = this.state;
    const { onCancel } = this.props;
    localStorage.setItem("hly.commonFunction", JSON.stringify(this.state.commonFunc));
    localStorage.setItem(`hly.menuConfig.${tenantMode ? "tenantMode" : "companyMode"}`, JSON.stringify(menuConfig));
    this.initSettingConfig();
    onCancel();
    message.error(messages('personal-setting.key25')/*您保存的设置将在您下一次刷新页面后生效哦*/)
  };

  renderMenuList = menu => menu.filter((menuItem) => mainService.checkMenuAuth(menuItem, this.props.adminMode, this.props.tenantMode, this.props.isOldCompany)).map(item => (
    <div onClick={() => this.handleClickMenu(item)}
         className={`menu-item ${this.state.selectedKey === item.key && 'selected'} cursor-move`}
         key={item.key}
    >
      <span>
        <span className="nav-icon"
              onMouseDown={e => e.stopPropagation()}
              style={!item.subMenu ? {cursor: "pointer"} : {}}>
            {item.subMenu ? <Icon type={item.icon} className="operate-icon"/> : <Checkbox value={item.key}/>}
        </span>
        <span className="nav-text">{item.menuName ? item.menuName : messages(`menu.${item.key}`)}</span>
        {item.subMenu && <Icon type="right" className="arrow-right"/>}
      </span>
    </div>
  ));

  render() {
    const title = [['员工模式', '员工模式'], ['公司管理员模式', '集团管理员模式']];
    const { commonFunc, menu, selectedKey, animatedFlag, menuConfig } = this.state;
    const { tenantMode, adminMode, visible, onCancel } = this.props;
    let tenantmode = tenantMode ? "TENANT_MODE" : "COMPANY_MODE";
    let adminmode = adminMode ? "ADMIN_MODE" : "PERSONAL_MODE";
    let totalLength = commonFunc.PERSONAL_MODE.length + commonFunc.ADMIN_MODE[tenantmode].length;
    let value = adminMode ? commonFunc[adminmode][tenantmode] : commonFunc.PERSONAL_MODE;
    return (
      <Modal
        title={`${title[Number(adminMode)][Number(tenantMode)]}下的菜单设置`}
        className="menu-sort"
        width={950}
        visible={visible}
        onCancel={() => onCancel()}
        onOk={this.onSaveConfig}
      >
        <div className="menu-list">
          <Row>
            <Col span={16}>
              <h3>{messages('personal-setting.key50')/*个性化导航排序*/}</h3>
              <div className="menu-list-left">
                <Checkbox.Group onChange={this.handleCheckMenu} value={value}>
                  <Row>
                    <Col span={12} style={{overflow: "hidden"}}>
                      {
                        menu && menu.length && (
                          <div className="menu-list-item">
                            <ListSort onChange={this.handleSortMenu}>
                              {this.renderMenuList(sortMenu(menu, Object.keys(menuConfig)))}
                            </ListSort>
                          </div>
                        )
                      }
                    </Col>
                    <Col span={12} style={{overflow: "hidden", padding: "0 0 0 10px"}}>
                      {selectedKey && animatedFlag && (
                        <div className="menu-list-item">
                          <ListSort onChange={this.handleSortSubMenu}>
                            {this.renderMenuList(sortMenu(menuRoute.getMenuItemByAttr(selectedKey, 'key').subMenu, menuConfig[selectedKey]))}
                          </ListSort>
                        </div>
                      )}
                    </Col>
                  </Row>
                </Checkbox.Group>
              </div>
            </Col>

            <Col span={18}>
              <h3>{messages('personal-setting.key54')/*常用功能*/}</h3>
              <div className="tag-box">
                {
                  totalLength ? (
                    <div>
                      <div className={"tag-list"}>
                        <h4>{messages('personal-setting.key61')/*个人常用*/}</h4>
                        {
                          commonFunc.PERSONAL_MODE.map((item) => {
                            return (
                              <Tag
                                closable
                                afterClose={() => this.onCloseTag(item, "PERSONAL_MODE")}
                                key={item}
                              >
                                {messages(`menu.${item}`)}
                              </Tag>
                            )
                          })
                        }
                      </div>
                      {
                        this.hasAnyAuthorities(['ROLE_TENANT_ADMIN', 'ROLE_COMPANY_ADMIN']) && (
                          <div className={"tag-list"}>
                            <h4>{messages('personal-setting.key62')/*管理员常用*/}</h4>
                            {
                              commonFunc.ADMIN_MODE[tenantmode].map((item) => {
                                return (
                                  <Tag closable
                                       afterClose={() => this.onCloseTag(item, "ADMIN_MODE")}
                                       key={item}>{messages(`menu.${item}`)}</Tag>
                                )
                              })
                            }
                          </div>
                        )}
                    </div>
                  ) : (
                    <div className="null-data">
                      <p><img src={NullDataImg}/></p>
                      <p>{messages('personal-setting.key63')/*暂无常用功能*/}</p>
                    </div>
                  )
                }
              </div>
            </Col>
          </Row>
        </div>
      </Modal>
    );
  }
}

MenuSort.defaultProps = {};

MenuSort.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    tenantMode: state.main.tenantMode,//集团模式
    adminMode: state.main.adminMode,//管理员模式
    isOldCompany: state.login.isOldCompany,
  }
}

export default connect(mapStateToProps)(MenuSort);

